Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources

In [36]:
# Make all necessary imports.
import warnings
warnings.filterwarnings('ignore')
In [37]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import time

import numpy as np
import matplotlib.pyplot as plt

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
In [38]:
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [39]:
# Load the dataset with TensorFlow Datasets.
# Create a training set, a validation set and a test set 
(training_set, validation_set, test_set), dataset_info = tfds.load('oxford_flowers102', split=['train', 'validation', 'test'], as_supervised=True, with_info=True, shuffle_files=True)
Downloading and preparing dataset oxford_flowers102 (336.76 MiB) to /root/tensorflow_datasets/oxford_flowers102/0.0.1...










Dataset oxford_flowers102 downloaded and prepared to /root/tensorflow_datasets/oxford_flowers102/0.0.1. Subsequent calls will reuse this data.

Explore the Dataset

In [40]:
# Get the number of examples in each set from the dataset info.
num_training = dataset_info.splits['train'].num_examples
num_validation = dataset_info.splits['validation'].num_examples
num_test = dataset_info.splits['test'].num_examples
# Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes

print('The train data size is: ', num_training)
print('The validation data size is: ', num_validation)
print('The test data size is: ', num_test)

print('The number of labels is: ', num_classes)
The train data size is:  1020
The validation data size is:  1020
The test data size is:  6149
The number of labels is:  102
In [41]:
# Print the shape and corresponding label of 3 images in the training set.
for image, label in training_set.take(3):
    image = image.numpy()
    label = label.numpy()
    
    print('\nImage Shape: ',image.shape)
    print('Image Label: ',label)
Image Shape:  (752, 500, 3)
Image Label:  60

Image Shape:  (500, 666, 3)
Image Label:  52

Image Shape:  (711, 500, 3)
Image Label:  3
In [42]:
# Plot 1 image from the training set. Set the title 
# of the plot to the corresponding image label. 
for image, label in training_set.take(1):
    image = image.numpy()
    label = label.numpy()
   
    plt.imshow(image)
    plt.title(label)
    plt.show()

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [43]:
import json

with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [44]:
# Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 
for image, label in training_set.take(1):
    image = image.numpy()
    label = label.numpy()
    
    flower_name = class_names[str(label + 1)]
    
    plt.imshow(image)
    plt.title('Flower name: '+ flower_name)
    plt.show()

Create Pipeline

In [45]:
# Create a pipeline for each set.
# MobileNet requires images 224x224
BATCH_SIZE = 64
IMG_SHAPE = 224

def normalize(image, label):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (IMG_SHAPE, IMG_SHAPE))
    image /= 255
    return image, label

def augment(image,label):
    image, label = normalize(image, label)
    image = tf.image.random_flip_left_right(image)
    image = tf.image.random_contrast(image, 0.9, 1.1)
    image = tf.image.random_brightness(image, max_delta=0.5) # Random brightness
    return image,label

training_batches = training_set.shuffle(num_training//4).map(augment).batch(BATCH_SIZE).prefetch(1)
validation_batches = validation_set.map(normalize).batch(BATCH_SIZE).prefetch(1)
test_batches = validation_set.map(normalize).batch(BATCH_SIZE).prefetch(1)

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [46]:
# Load MobileNet
URL = 'https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4'

mobile_net_features = hub.KerasLayer(URL, input_shape=(IMG_SHAPE, IMG_SHAPE, 3))

# Freeze the pre-trained model
mobile_net_features.trainable = False
In [56]:
# Build and train your network.
model = tf.keras.Sequential([
    mobile_net_features,
    tf.keras.layers.Dense(160, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(102, activation='softmax')
])

model.compile(optimizer='adam',
             loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])

early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)
save_best = tf.keras.callbacks.ModelCheckpoint('./best_model.h5', monitor='val_loss', save_best_only=True)

history = model.fit(training_batches,
                   epochs=100,
                   validation_data = validation_batches,
                   callbacks=[early_stopping])

model.summary()
Epoch 1/100
16/16 [==============================] - 10s 604ms/step - loss: 4.6272 - accuracy: 0.0245 - val_loss: 0.0000e+00 - val_accuracy: 0.0000e+00
Epoch 2/100
16/16 [==============================] - 7s 438ms/step - loss: 4.2734 - accuracy: 0.0814 - val_loss: 3.9841 - val_accuracy: 0.1863
Epoch 3/100
16/16 [==============================] - 7s 442ms/step - loss: 3.7835 - accuracy: 0.1745 - val_loss: 3.3552 - val_accuracy: 0.3422
Epoch 4/100
16/16 [==============================] - 7s 441ms/step - loss: 3.1126 - accuracy: 0.2971 - val_loss: 2.6726 - val_accuracy: 0.4510
Epoch 5/100
16/16 [==============================] - 7s 449ms/step - loss: 2.5703 - accuracy: 0.3755 - val_loss: 2.2235 - val_accuracy: 0.5333
Epoch 6/100
16/16 [==============================] - 7s 451ms/step - loss: 2.1138 - accuracy: 0.4510 - val_loss: 1.8414 - val_accuracy: 0.6127
Epoch 7/100
16/16 [==============================] - 7s 453ms/step - loss: 1.8280 - accuracy: 0.5167 - val_loss: 1.5811 - val_accuracy: 0.6539
Epoch 8/100
16/16 [==============================] - 7s 468ms/step - loss: 1.5380 - accuracy: 0.5922 - val_loss: 1.4134 - val_accuracy: 0.6706
Epoch 9/100
16/16 [==============================] - 7s 454ms/step - loss: 1.2998 - accuracy: 0.6696 - val_loss: 1.2707 - val_accuracy: 0.6951
Epoch 10/100
16/16 [==============================] - 7s 455ms/step - loss: 1.1660 - accuracy: 0.6931 - val_loss: 1.1897 - val_accuracy: 0.7127
Epoch 11/100
16/16 [==============================] - 7s 451ms/step - loss: 0.9986 - accuracy: 0.7343 - val_loss: 1.1177 - val_accuracy: 0.7186
Epoch 12/100
16/16 [==============================] - 7s 455ms/step - loss: 0.8976 - accuracy: 0.7480 - val_loss: 1.0573 - val_accuracy: 0.7363
Epoch 13/100
16/16 [==============================] - 8s 484ms/step - loss: 0.8206 - accuracy: 0.7873 - val_loss: 0.9923 - val_accuracy: 0.7363
Epoch 14/100
16/16 [==============================] - 8s 477ms/step - loss: 0.7201 - accuracy: 0.8000 - val_loss: 0.9449 - val_accuracy: 0.7490
Epoch 15/100
16/16 [==============================] - 7s 455ms/step - loss: 0.6201 - accuracy: 0.8304 - val_loss: 0.9988 - val_accuracy: 0.7343
Epoch 16/100
16/16 [==============================] - 7s 455ms/step - loss: 0.6669 - accuracy: 0.8216 - val_loss: 0.9174 - val_accuracy: 0.7549
Epoch 17/100
16/16 [==============================] - 7s 450ms/step - loss: 0.5802 - accuracy: 0.8441 - val_loss: 0.8606 - val_accuracy: 0.7657
Epoch 18/100
16/16 [==============================] - 7s 442ms/step - loss: 0.5071 - accuracy: 0.8745 - val_loss: 0.8420 - val_accuracy: 0.7853
Epoch 19/100
16/16 [==============================] - 7s 440ms/step - loss: 0.4199 - accuracy: 0.8971 - val_loss: 0.8145 - val_accuracy: 0.7824
Epoch 20/100
16/16 [==============================] - 7s 437ms/step - loss: 0.4313 - accuracy: 0.8814 - val_loss: 0.8125 - val_accuracy: 0.7794
Epoch 21/100
16/16 [==============================] - 7s 443ms/step - loss: 0.4222 - accuracy: 0.8843 - val_loss: 0.8054 - val_accuracy: 0.7637
Epoch 22/100
16/16 [==============================] - 7s 450ms/step - loss: 0.3686 - accuracy: 0.9039 - val_loss: 0.7834 - val_accuracy: 0.7833
Epoch 23/100
16/16 [==============================] - 7s 448ms/step - loss: 0.3553 - accuracy: 0.9049 - val_loss: 0.7638 - val_accuracy: 0.7931
Epoch 24/100
16/16 [==============================] - 7s 444ms/step - loss: 0.3184 - accuracy: 0.9176 - val_loss: 0.7608 - val_accuracy: 0.7990
Epoch 25/100
16/16 [==============================] - 7s 451ms/step - loss: 0.2792 - accuracy: 0.9314 - val_loss: 0.7469 - val_accuracy: 0.7941
Epoch 26/100
16/16 [==============================] - 7s 453ms/step - loss: 0.2986 - accuracy: 0.9255 - val_loss: 0.7346 - val_accuracy: 0.7971
Epoch 27/100
16/16 [==============================] - 7s 452ms/step - loss: 0.2916 - accuracy: 0.9235 - val_loss: 0.7582 - val_accuracy: 0.7951
Epoch 28/100
16/16 [==============================] - 7s 451ms/step - loss: 0.2972 - accuracy: 0.9167 - val_loss: 0.7451 - val_accuracy: 0.7902
Epoch 29/100
16/16 [==============================] - 7s 452ms/step - loss: 0.2511 - accuracy: 0.9343 - val_loss: 0.7268 - val_accuracy: 0.7941
Epoch 30/100
16/16 [==============================] - 7s 455ms/step - loss: 0.2278 - accuracy: 0.9461 - val_loss: 0.7392 - val_accuracy: 0.7912
Epoch 31/100
16/16 [==============================] - 7s 450ms/step - loss: 0.2475 - accuracy: 0.9353 - val_loss: 0.7435 - val_accuracy: 0.7922
Epoch 32/100
16/16 [==============================] - 7s 454ms/step - loss: 0.2000 - accuracy: 0.9510 - val_loss: 0.7153 - val_accuracy: 0.7980
Epoch 33/100
16/16 [==============================] - 7s 468ms/step - loss: 0.1905 - accuracy: 0.9510 - val_loss: 0.7246 - val_accuracy: 0.7892
Epoch 34/100
16/16 [==============================] - 7s 458ms/step - loss: 0.2125 - accuracy: 0.9402 - val_loss: 0.7334 - val_accuracy: 0.8059
Epoch 35/100
16/16 [==============================] - 7s 451ms/step - loss: 0.1865 - accuracy: 0.9529 - val_loss: 0.7132 - val_accuracy: 0.8088
Epoch 36/100
16/16 [==============================] - 7s 448ms/step - loss: 0.1871 - accuracy: 0.9490 - val_loss: 0.7038 - val_accuracy: 0.8049
Epoch 37/100
16/16 [==============================] - 7s 451ms/step - loss: 0.1829 - accuracy: 0.9510 - val_loss: 0.7256 - val_accuracy: 0.7922
Epoch 38/100
16/16 [==============================] - 7s 454ms/step - loss: 0.1574 - accuracy: 0.9598 - val_loss: 0.7126 - val_accuracy: 0.8020
Epoch 39/100
16/16 [==============================] - 7s 452ms/step - loss: 0.1615 - accuracy: 0.9637 - val_loss: 0.7167 - val_accuracy: 0.7951
Epoch 40/100
16/16 [==============================] - 7s 451ms/step - loss: 0.1478 - accuracy: 0.9676 - val_loss: 0.6944 - val_accuracy: 0.8059
Epoch 41/100
16/16 [==============================] - 7s 454ms/step - loss: 0.1641 - accuracy: 0.9667 - val_loss: 0.7223 - val_accuracy: 0.8020
Epoch 42/100
16/16 [==============================] - 7s 451ms/step - loss: 0.1664 - accuracy: 0.9588 - val_loss: 0.7313 - val_accuracy: 0.7961
Epoch 43/100
16/16 [==============================] - 7s 453ms/step - loss: 0.1337 - accuracy: 0.9637 - val_loss: 0.7331 - val_accuracy: 0.8049
Epoch 44/100
16/16 [==============================] - 7s 450ms/step - loss: 0.1266 - accuracy: 0.9686 - val_loss: 0.7369 - val_accuracy: 0.7990
Epoch 45/100
16/16 [==============================] - 7s 457ms/step - loss: 0.1240 - accuracy: 0.9676 - val_loss: 0.7422 - val_accuracy: 0.8010
Epoch 46/100
16/16 [==============================] - 7s 453ms/step - loss: 0.1205 - accuracy: 0.9647 - val_loss: 0.7017 - val_accuracy: 0.8000
Epoch 47/100
16/16 [==============================] - 7s 451ms/step - loss: 0.1419 - accuracy: 0.9598 - val_loss: 0.7159 - val_accuracy: 0.8049
Epoch 48/100
16/16 [==============================] - 7s 453ms/step - loss: 0.1025 - accuracy: 0.9755 - val_loss: 0.7169 - val_accuracy: 0.8000
Epoch 49/100
16/16 [==============================] - 7s 451ms/step - loss: 0.1140 - accuracy: 0.9696 - val_loss: 0.7235 - val_accuracy: 0.8000
Epoch 50/100
16/16 [==============================] - 7s 469ms/step - loss: 0.1305 - accuracy: 0.9716 - val_loss: 0.6960 - val_accuracy: 0.8176
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dense_3 (Dense)              (None, 160)               204960    
_________________________________________________________________
dropout_2 (Dropout)          (None, 160)               0         
_________________________________________________________________
dense_4 (Dense)              (None, 128)               20608     
_________________________________________________________________
dropout_3 (Dropout)          (None, 128)               0         
_________________________________________________________________
dense_5 (Dense)              (None, 102)               13158     
=================================================================
Total params: 2,496,710
Trainable params: 238,726
Non-trainable params: 2,257,984
_________________________________________________________________
In [57]:
# Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range = range(len(training_accuracy))

plt.figure(figsize=(12, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.title('Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.title('Loss')

plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [58]:
# Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(test_batches)
    
print('\nLoss: {:,.3f}'.format(loss))
print('Accuracy: {:,.3f}'.format(accuracy))
16/16 [==============================] - 3s 197ms/step - loss: 0.6960 - accuracy: 0.8176

Loss: 0.696
Accuracy: 0.818
In [59]:
#Check the model's performance on a set of images
for image_batch, label_batch in test_batches.take(1):
    pred = model.predict(image_batch)
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()
    
plt.figure(figsize=(12, 12))

for i in range(20):
    plt.subplot(5, 4, i + 1)
    plt.imshow(images[i], cmap = plt.cm.binary)
    label = np.argmax(pred[i])
    flower_name = (class_names[str(label + 1)])
    color = 'green' if np.argmax(pred[i]) == labels[i] else 'red'
    plt.title(flower_name, color=color)
    plt.axis('off')

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [60]:
# Save your trained model as a Keras model.
t = time.time()

model_filepath = './flower_model_{}.h5'.format(int(t))

model.save(model_filepath)

Load the Keras Model

Load the Keras model you saved above.

In [4]:
# Load the Keras model
#best_model = './best_model.h5'

reloaded_model = tf.keras.models.load_model(model_filepath,custom_objects={'KerasLayer':hub.KerasLayer})
#reloaded_model = tf.keras.models.load_model(newest_model_fp,custom_objects={'KerasLayer':hub.KerasLayer})
reloaded_model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dense_4 (Dense)              (None, 160)               204960    
_________________________________________________________________
dropout (Dropout)            (None, 160)               0         
_________________________________________________________________
dense_5 (Dense)              (None, 128)               20608     
_________________________________________________________________
dropout_1 (Dropout)          (None, 128)               0         
_________________________________________________________________
dense_6 (Dense)              (None, 102)               13158     
=================================================================
Total params: 2,496,710
Trainable params: 238,726
Non-trainable params: 2,257,984
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [61]:
# Create the process_image function
def process_image(img):
    img = tf.cast(img, tf.float32)
    img = tf.image.resize(img, (IMG_SHAPE, IMG_SHAPE))
    img /= 255
    return img.numpy()    

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [62]:
IMG_SHAPE = 224
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [63]:
# Create the predict function
def predict(img_path, model, k=5):
    im = Image.open(img_path)
    image = np.asarray(im)
    
    processed_image = process_image(image)
    expanded_image = np.expand_dims(processed_image, axis=0)
    prediction = model.predict(expanded_image)[0]
    
    k *= -1 # for use with argpartition
    classes = np.argpartition(prediction, k)[k:] # take top k classes
    probs = prediction[classes]
    classes = [str(c) for c in classes] # Convert to string for dict lookup

    return probs, classes

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [64]:
# Plot the input image along with the top 5 classes
image_path = './test_images/'

for img in ['cautleya_spicata.jpg', 'hard-leaved_pocket_orchid.jpg', 'orange_dahlia.jpg', 'wild_pansy.jpg']:
    full_path = image_path + img

    probs, classes = predict(full_path, reloaded_model)
    
    im = Image.open(full_path)
    current_image = np.asarray(im)
    
    fig, (ax1, ax2) = plt.subplots(figsize=(10,5), ncols=2)
    ax1.imshow(current_image)
    ax1.set_title('Sample Image: ' + img)
    
    flower_names = [class_names[str(int(c) + 1)] for c in classes]
    ax2.barh(flower_names, probs, align='center', alpha=0.5)
    ax2.set_title('Class Probability')
    ax2.set_xlim([0, 1.1])
    ax2.set_yticklabels(flower_names)
    
    plt.tight_layout()
    plt.show()
In [ ]: